//
//  LXStatusPictureView.swift
//  weibo
//
//  Created by lixin on 16/4/22.
//  Copyright © 2016年 lixin. All rights reserved.
//

import UIKit

private let LXStatusPictureViewCellId = "LXStatusPictureViewCellId"

private let itemMargin: CGFloat = 5

private let cellWH: CGFloat = (SCREENW - 20 - itemMargin * 2) / 3

class LXStatusPictureView: UICollectionView {
    
    var pictureInfo: [LXPicInfo]?{
        
        didSet{
            
            let size = getPictureViewSize(pictureInfo?.count ?? 0)
            
            self.snp_updateConstraints { (make) -> Void in
                
                make.size.equalTo(size)
            }
            
            //一定要刷新数据
            self.reloadData()
            
        }
    }
    
    // 处理配图size
    func getPictureViewSize(count: Int) -> CGSize{
        
        let col = count >= 3 ? 3 : count
        
        let row = (count - 1) / 3 + 1
    
        let width = CGFloat(col) * cellWH + CGFloat(col - 1) * itemMargin
        
        let height = CGFloat(row) * cellWH + CGFloat(row - 1) * itemMargin
        
        return CGSize(width: width, height: height)
    }
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 视图设置
    private func setUI(){
        
        self.backgroundColor = UIColor.clearColor()
        
        dataSource = self
        
        delegate = self
        
        //注册cell
        registerClass(CZStatusPictureViewCell.self, forCellWithReuseIdentifier: LXStatusPictureViewCellId)
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        
        layout.minimumInteritemSpacing = itemMargin
        
        layout.minimumLineSpacing = itemMargin
        
    }
    
}

extension LXStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate{
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictureInfo?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 实例化图片浏览器
        let photoBrowser = SDPhotoBrowser()
        
        photoBrowser.delegate = self
        
        photoBrowser.currentImageIndex = indexPath.item
        
        photoBrowser.imageCount = self.pictureInfo!.count
        
        // 设置父控件
        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.show()
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LXStatusPictureViewCellId, forIndexPath: indexPath) as! CZStatusPictureViewCell
        
        cell.pic = pictureInfo![indexPath.item]
        
        return cell
    }
}

class CZStatusPictureViewCell: UICollectionViewCell {
    
    var pic: LXPicInfo?{
        
        didSet{
            
            bgImageView.sd_setImageWithURL(NSURL(string: pic?.thumbnail_pic ?? ""), placeholderImage: UIImage(named: "timeline_card_top_background"))
            
            if let p = pic?.thumbnail_pic where p.hasSuffix(".gif") {
                
                gifImageView.hidden = false
                
            }else{
                
                gifImageView.hidden = true
            }
        }
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setUI(){
        
        self.backgroundColor = UIColor.whiteColor()
        
        contentView.addSubview(bgImageView)
        
        contentView.addSubview(gifImageView)
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        gifImageView.snp_makeConstraints { (make) -> Void in
            
            make.trailing.bottom.equalTo(contentView)
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var bgImageView: UIImageView = {
        
        let img = UIImageView(image: UIImage(named: "timeline_card_top_background"))
        
        img.contentMode = .ScaleAspectFill
        
        img.clipsToBounds = true
        
        return img
    }()
    
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}

extension LXStatusPictureView: SDPhotoBrowserDelegate{
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        
        let cell = self.cellForItemAtIndexPath(indexPath) as! CZStatusPictureViewCell
        
        return cell.bgImageView.image
    }
    
    // 返回高质量图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let urlStr = (self.pictureInfo![index].thumbnail_pic ?? "" as NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlStr)
    }
}
